package com.test.converttest.convertors;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.util.StrutsTypeConverter;

import javax.servlet.ServletContext;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/9/11 15:40
 */
public class DateConvertor extends StrutsTypeConverter {
    private DateFormat dateFormat;

    public DateConvertor() {
        System.out.println("DateConvertor create");
    }

    private DateFormat getDateFormat() {
        if (this.dateFormat == null) {
            // 获取当前WEB应用的初始化参数datePattern
            ServletContext context = ServletActionContext.getServletContext();
            String format = context.getInitParameter("datePattern");
            dateFormat = new SimpleDateFormat(format);
        }
        return this.dateFormat;
    }

    @Override
    public Object convertFromString(Map context, String[] values, Class toClass) {
        System.out.println("convertFromString");
        if (toClass == Date.class) {
            if (ArrayUtils.isNotEmpty(values)) {
                String value = values[0];
                try {
                    return getDateFormat().parse(value);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        // 若没有转换成功，则返回values
        return values;
    }

    @Override
    public String convertToString(Map context, Object o) {
        System.out.println("convertToString");
        if (o instanceof Date) {
            return getDateFormat().format((Date) o);
        }
        // 若转换失败，则返回空
        return null;
    }
}
